package com.leetcode;

import com.leetcode.common.ListNode;

/**
 * 19. 删除链表的倒数第 N 个结点
 * 双指针法
 * 
 * @author fy
 * @date 2022/4/11 16:26
 */
public class Solution19_2 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || n <= 0) {
            return head;
        }
        ListNode dummyHead = new ListNode(-1, head);
        ListNode p = dummyHead;
        ListNode q = dummyHead.next;
        for (int i = 0; i < n; i++) {
            if (q == null) {
                throw new RuntimeException("n is wrong");
            }
            q = q.next;
        }
        while (q != null) {
            p = p.next;
            q = q.next;
        }
        p.next = p.next.next;
        return dummyHead.next;
    }
    
}
